"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_promise_1 = __importDefault(require("fs-promise"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const stream_1 = require("stream");
const promises_1 = require("stream/promises");
async function saveToFile(fileSavePath, buffer) {
    if (fileSavePath && buffer) {
        const filePath = path_1.default.join(fileSavePath.replaceAll('\\', '/').replaceAll('//', '/'));
        await fs_promise_1.default.ensureDir(path_1.default.dirname(filePath));
        const bufferStream = stream_1.Readable.from(buffer, { objectMode: false });
        const writeStream = fs_1.default.createWriteStream(filePath, { emitClose: true });
        try {
            await (0, promises_1.finished)(bufferStream.pipe(writeStream, { end: true }));
        }
        catch (err) {
            fs_1.default.rm(filePath, () => {
                console.log('清理未完整写入的文件');
            });
            throw new Error(`写入失败: ${err.message}`);
        }
        fs_1.default.writeFileSync(filePath, buffer);
    }
}
exports.default = saveToFile;
